package com.quanshu.exchange.ui.gui.message.chat.row;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMVideoMessageBody;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ShowVideoActivity extends BaseActivity {
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;

    private String localFilePath;
    private File localFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_show_video);
        ButterKnife.bind(this);

        final EMMessage message = getIntent().getParcelableExtra("msg");
        if (!(message.getBody() instanceof EMVideoMessageBody)) {
            ToastHelper.toast("消息格式不支持");
            finish();
            return;
        }
        EMVideoMessageBody messageBody = (EMVideoMessageBody) message.getBody();
        localFilePath = messageBody.getLocalUrl();
        localFile = new File(localFilePath);
        if (localFilePath != null && localFile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri contentUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                contentUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".FileProvider", localFile);
                grantUriPermission(getPackageName(), contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

            } else {
                contentUri = Uri.fromFile(localFile);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            intent.setDataAndType(contentUri, "video/*");
            startActivity(intent);
            finish();

        } else {
            downloadVideo(message);
        }
    }

    /**
     * show local video
     *
     * @param localPath -- local path of the video file
     */
    private void showLocalVideo(String localPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri contentUri;
        File tmpFile = new File(localPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".FileProvider", tmpFile);
            grantUriPermission(getPackageName(), contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

        } else {
            contentUri = Uri.fromFile(tmpFile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setDataAndType(contentUri, "video/*");
        startActivity(intent);
        finish();
    }

    /**
     * download video file
     */
    private void downloadVideo(EMMessage message) {
        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    loadingLayout.setVisibility(View.GONE);
                    progressBar.setProgress(0);
                    showLocalVideo(localFilePath);
                });
            }

            @Override
            public void onProgress(final int progress, String status) {
                runOnUiThread(() -> progressBar.setProgress(progress));
            }

            @Override
            public void onError(int error, String msg) {
                File file = new File(localFilePath);
                if (file.exists()) {
                    file.delete();
                }
            }
        });
        EMClient.getInstance().chatManager().downloadAttachment(message);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

}